﻿using System;
using System.Linq;
using System.Xml;

namespace HuaXingSDK
{
    public abstract class HXEncryptXml : HXXml
    {
        private const string XMLPARA = "XMLPARA";

        protected abstract string[] GetEncrypt();

        public virtual XmlDocument ToEncryptXml()
        {
            var xml = ToXml();
            if (xml.DocumentElement == null)
                throw new HXException("没有找到根节点。");

            var body = xml.DocumentElement.GetNodeByName("body");
            if (body == null)
                throw new HXException("没找到body节点。");

            var names = GetEncrypt();
            var para = CreateXmlNode(XMLPARA);

            foreach (var node in body.ChildNodes.ToArray())
            {
                if (names.Any(i => i.Equals(node.Name, StringComparison.OrdinalIgnoreCase)))
                {
                    para.AppendChild(node);
                }
            }

            if (para.HasChildNodes)
            {
                para.InnerText = Uilts.Encrypt3DES(HXConfigs.TripleDESKey, para.InnerXml);
                body.AppendChild(para);
            }

            return xml;
        }
    }
}
